package com.srwl.mytx.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.core.widget.NestedScrollView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.bm.library.Info;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.smarx.notchlib.INotchScreen;
import com.smarx.notchlib.NotchScreenManager;
import com.srwl.easeui.widget.MyTitleBar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.MenuArrayAdapter;
import com.srwl.mytx.adapter.PickPictureAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.FileUpLoad;
import com.srwl.mytx.domain.LatLng;
import com.srwl.mytx.domain.LiveRoom;
import com.srwl.mytx.domain.MyFile;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.map.GaodeLocationClient;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.FileUtils;
import com.srwl.mytx.utils.GlideEngine;
import com.srwl.mytx.utils.PermissionsUtils;
import com.srwl.mytx.utils.SoftKeyboardFixerForFullscreen;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.PreviewSelectFilePageView;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.AgreementDialog;
import com.srwl.mytx.widget.PickPicturesListView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.srwl.mytx.contrack.GoodsConstrack.GOODS_STATUS_NORMAL;


public class CreateLiveRoomActivity extends BaseActivity implements PickPictureAdapter.InteractionListener, PreviewSelectFilePageView.GetPhotoViewInfoListener, PermissionsUtils.IPermissionsResult {
    private static String TAG = CreateLiveRoomActivity.class.getSimpleName();
    private static final int REQUEST_CODE_PICTURE_CHOOSE = 1;
    private static final int REQUEST_CODE_RECORD_VIDEO = 2;
    private static final int REQUEST_CODE_LOCATION = 3;
    private static final String LIVE_ROOM_TYPE_AREA = "地区";
    private static final String LIVE_ROOM_TYPE_INDUSTRY = "行业";
    private static final String LIVE_ROOM_TYPE_SCHOOL = "学校";
    private long lastClickTime = 0L;
    //private static final int FAST_CLICK_DELAY_TIME = 500;  // 快速点击间隔

    @BindView(R.id.rv_add_picture)
    PickPicturesListView picturesListView;
    @BindView(R.id.et_content)
    EditText et_content;
    @BindView(R.id.et_title)
    EditText et_title;

    @BindView(R.id.fl_bigPicture)
    View fl_bigPicture;
    @BindView(R.id.img_bg_black)
    ImageView iv_background;
    @BindView(R.id.title_bar)
    MyTitleBar titleBar;
    @BindView(R.id.sv_container)
    NestedScrollView sv_container;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.big_picture_page_view)
    PreviewSelectFilePageView previewSelectFilePageView;
    @BindView(R.id.rl_location)
    RelativeLayout rl_location;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.btn_publish)
    Button btn_publish;
    private int pictureLimit = 9;//默认设置9张图片
    private int videoLimit = 1;//默认设置1个视频
    private ArrayList<MyFile> totalSelectFile = new ArrayList<>();
    private ArrayList<MyFile> selectRemotePictures = new ArrayList<>();//选择的历史图片 文件
    private ArrayList<MyFile> selectRemoteVideos = new ArrayList<>();//选择的历史 视频文件
    private ArrayList<MyFile> selectLocalPictures = new ArrayList<>();//选择的本地 图片文件
    private ArrayList<MyFile> selectLocalVideos = new ArrayList<>();//选择的本地 视频文件
    private ArrayList<Photo> selectPhotos = new ArrayList<>();//本地圖片 path 集合
    private GaodeLocationClient location;

    private String str_address;

    private LatLng latLng;


    //视频封面图片
    private String framePicPath;
    //视频大小
    private int videoSize;
    //主题分类
    private Integer topicType;
    private boolean isSaved;
    private boolean hasNotch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_live_room);
        ButterKnife.bind(this);
        View statusBar = findViewById(R.id.status_bar);
        NotchScreenManager.getInstance().getNotchInfo(this, new INotchScreen.NotchScreenCallback() {
            @Override
            public void onResult(INotchScreen.NotchScreenInfo notchScreenInfo) {
                hasNotch = notchScreenInfo.hasNotch;
                Log.i(TAG, "Is this screen notch? " + hasNotch);
                if (hasNotch) {
                    statusBar.setVisibility(View.GONE);
                } else {
                    //如果不是刘海屏，就设置为全屏
                    SoftKeyboardFixerForFullscreen.assistActivity(CreateLiveRoomActivity.this);
                    setupStartBar();
                    int statusBarHeight = Utils.getStatusBarHeight(CreateLiveRoomActivity.this);
                    if (statusBarHeight != 0) {
                        ViewGroup.LayoutParams layoutParams = statusBar.getLayoutParams();
                        layoutParams.height = statusBarHeight;
                        statusBar.setLayoutParams(layoutParams);
                    }
                }
                previewSelectFilePageView.init(totalSelectFile, CreateLiveRoomActivity.this, hasNotch);
            }
        });
        picturesListView.init(totalSelectFile, this);
        initLocation();
        initTitleBar();
        sv_container.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                hideSoftKeyboard();
            }
        });
        DisplayMetrics dm = new DisplayMetrics();

        AgreementDialog agreement = new AgreementDialog(this, R.array.create_live_room_agreement);
        agreement.setCanceledOnTouchOutside(false);
        agreement.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                Log.d(TAG, "onDismiss: 开始做创建权限校验..........");
                checkCreateAuthority();
            }
        });
        agreement.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        agreement.show();
        //控制dialog 的宽高，必须放在 show 之后
        WindowManager.LayoutParams params = agreement.getWindow().getAttributes();//获取对话框当前的参数值
//        params.height = (int) (screenHeight * 0.9);
        params.width = (screenWidth);
        agreement.getWindow().setAttributes(params);

    }

    /**
     * 检查是否有创建焦点权限
     */
    private void checkCreateAuthority() {
        if (!Helper.getInstance().isNetworkConnected()) {
            showQuiteDialog("当前没有网络，请稍后再试");
            return;
        }
        //本不需要携带参数，但是为了携带token 到后端，不携带其他参数的情况下，必须以 JSONObject 放入 token 后，作为body ,再做请求
        JSONObject body = new JSONObject();
        body.put("token", UserProfileManager.getInstance().getLoginUserInfo().getToken());
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .checkAuthorityCreateLiveRoom(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult body = response.body();
                        if (!response.isSuccessful() || body == null) {
                            showQuiteDialog("创建权限校验未能成功执行，请稍后再试");
                            return;
                        }
                        if (body.isError()) {
                            Log.e(TAG, "onResponse: " + body.getMsg());
                            if (body.getStatus() == Constant.CREATED_LIVE_ROOM_LIMIT) {
                                showQuiteDialog("您已经是焦点[" + body.getMsg() + "]的管理员，不能再创建焦点");
                            } else {
                                showQuiteDialog("创建权限校验未通过，请稍后再试");
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        showQuiteDialog("创建权限校验未成功执行，请稍后再试");
                    }
                });
    }

    private void showQuiteDialog(String content) {
        ConfirmDialog dialog = new ConfirmDialog(this, "提示", content);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                finish();
            }
        });
        dialog.show();
    }

    private void initTitleBar() {

        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPress();
            }
        });
        final List<String> menuItems = new ArrayList<>();
        menuItems.add(LIVE_ROOM_TYPE_AREA);
        menuItems.add(LIVE_ROOM_TYPE_INDUSTRY);
        menuItems.add(LIVE_ROOM_TYPE_SCHOOL);

        titleBar.setRightTitle("分类");
        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideSoftKeyboard();
                final ListPopupWindow listPopupWindow = new ListPopupWindow(CreateLiveRoomActivity.this);
                listPopupWindow.setAdapter(new MenuArrayAdapter(CreateLiveRoomActivity.this, R.layout.right_menu_item, R.id.tv_dialog_item, menuItems));
                listPopupWindow.setAnchorView(titleBar.getRightLayout());
                listPopupWindow.setWidth(Utils.dpToPx(100, CreateLiveRoomActivity.this));
                listPopupWindow.setHeight(ListPopupWindow.WRAP_CONTENT);
                listPopupWindow.setHorizontalOffset(Utils.dpToPx(-5, CreateLiveRoomActivity.this));
                listPopupWindow.setVerticalOffset(Utils.dpToPx(3, CreateLiveRoomActivity.this));
                listPopupWindow.setDropDownGravity(Gravity.END);//设置对齐方式。
                listPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.tx_pop_bg_1));
                listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        titleBar.setRightTitle(menuItems.get(position));
                        switch (menuItems.get(position)) {
                            case LIVE_ROOM_TYPE_AREA:
                                topicType = Constant.TOPIC_TYPE_AREA;
                                break;
                            case LIVE_ROOM_TYPE_INDUSTRY:
                                topicType = Constant.TOPIC_TYPE_INDUSTRY;
                                break;
                            case LIVE_ROOM_TYPE_SCHOOL:
                                topicType = Constant.TOPIC_TYPE_SCHOOL;

                        }
                        listPopupWindow.dismiss();
                    }
                });
                listPopupWindow.show();
            }
        });
    }


    private void initLocation() {
        location = new GaodeLocationClient(this,true);
        location.setLocationListener(new GaodeLocationClient.LocationListener() {
            @Override
            public void locationSuccess(AMapLocation location) {
                latLng = new LatLng(location.getLatitude(), location.getLongitude());
                str_address = location.getAddress();
                tv_address.setText(str_address);
            }
        });
    }


    private void startRecordVideo() {
        long SDCardRemainMB = FileUtils.getSDFreeSize();
        if (SDCardRemainMB >= 0L && SDCardRemainMB < 2L) {
            showToast(getString(R.string.aliwx_no_enough_sdcard_size));
            return;
        }


        //ShortVideoKitProcesser.showRecordShortVideo(PublishTopicActivity.this, null, REQUEST_CODE_RECORD_VIDEO, SITUATION_FOR_PUBLISH, "high", 0, 0);//阿里百川短视频录制
        //  startActivityForResult(new Intent(this, VideoRecordActivity.class), REQUEST_CODE_RECORD_VIDEO);
        // startActivityForResult(new Intent(this, FFmpegVideoRecordActivity.class), REQUEST_CODE_RECORD_VIDEO);
        VideoRecordActivityV3.startActivity(this, REQUEST_CODE_RECORD_VIDEO, true);

    }

    private void showVideo(String videoPath) {
        Uri uri = Uri.parse("http://svideo.m.taobao.com/av/implayer.html");
        Intent intent = new Intent("android.intent.action.VIEW", uri, CreateLiveRoomActivity.this, MyVideoPlayActivity.class);
        intent.putExtra("localVideoPath", videoPath);
        intent.putExtra("framePicPath", framePicPath);
        intent.putExtra("videoSize", videoSize);
        startActivity(intent);
    }

    private String strTimeToDateFormat(String yearStr, String dateStr, String hourStr, String minuteStr) {

        return yearStr.replace("年", "-") + dateStr.replace("月", "-").replace("日", " ")
                + hourStr + ":" + minuteStr;
    }

    @OnClick(R.id.rl_location)
    void location() {
        Intent intent = new Intent(CreateLiveRoomActivity.this, PickLocationMapActivity.class);
        if (latLng != null) {
            intent.putExtra(PickLocationMapActivity.EXTRA_DATA_LATITUDE, latLng.getLatitude());
            intent.putExtra(PickLocationMapActivity.EXTRA_DATA_LONGITUDE, latLng.getLongitude());
        }
        startActivityForResult(intent, REQUEST_CODE_LOCATION);
    }

    @OnClick(R.id.rl_description)
    void desc() {
        et_content.setFocusable(true);
        et_content.setFocusableInTouchMode(true);
        et_content.requestFocus();
        inputMethodManager.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    @OnClick(R.id.btn_publish)
    void publish() {
        if (ClickUtil.isFastClick()) {
            return;
        }
        hideSoftKeyboard();
        if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
            startActivity(new Intent(this, LoginActivity.class).putExtra("EXTRA_CONTENT", "创建【焦点】需要先登录"));
            return;
        }
//        if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME){
//            //showToast("点的太快了，慢点试试");
//            return;
//        }
        lastClickTime = System.currentTimeMillis();

        if (topicType == null) {
            showToast("请在右上角选择分类");
            btn_publish.setEnabled(true);
            return;
        }
        // final AmapTopic topic = new AmapTopic();//如果是发布到自己的ElasticSearch,则应该是:Topic topic= new Topic;
        final Topic topic = new Topic();//如果是发布到自己的ElasticSearch,则应该是:Topic topic= new Topic;
        String str_title = et_title.getText().toString().trim();
        if (TextUtils.isEmpty(str_title)) {

            // Toast.makeText(PublishTopicActivity.this, "商品标题还没设置哦", Toast.LENGTH_LONG).show();
            showToast("标题没设置");
            btn_publish.setEnabled(true);
            return;
        }
        String str_content = et_content.getText().toString().trim();
        if (totalSelectFile.size() == 0) {

            showToast("图片和视频至少设置一样");
            btn_publish.setEnabled(true);
            return;
        }

        if (!TextUtils.isEmpty(str_content)) {
            topic.setContent(str_content);
        }
        //因为是保存在ES里面，所以每条发布的信息里面，都冗余保存发布者信息，也许这样是不科学的，以后再考量
        User loginUser = UserProfileManager.getInstance().getLoginUserInfo();

        topic.setTitle(str_title);
        User author = new User(loginUser.getuId());
        author.setAvatar(loginUser.getAvatar());
        author.setUsername(loginUser.getUsername());
        topic.setManager(author);

        //这两个时间为何在这儿设置呢，是因为这些数据传到服务端，没有转化成类，直接就保存到 ES上了，没法给里面添加创建和更新时间，
        //如果以后服务端收到这些数据是先转化成java类的话，就可以在客户端省略后面这两句，在服务端给加上这两个值即可。
        topic.setCreated(new Date());
        // topic.setUpdated(new Date());
        topic.setStatus(GOODS_STATUS_NORMAL);
        topic.setType(topicType);
        if (latLng != null) {
            topic.setLocation(latLng);
            topic.setAddress(str_address);

        } else {
            topic.setAddress(UserProfileManager.getInstance().getUserArea());
        }

        FileUpLoad fileUpLoad = new FileUpLoad(CreateLiveRoomActivity.this, totalSelectFile, new FileUpLoad.InteractionListener() {
            @Override
            public void onShowToast(String content) {
                showToast(findViewById(R.id.btn_publish), content);
            }

            @Override
            public void onShowProgressBar(String content) {
                showProgressDialog(content);
            }

            @Override
            public void onHideProgressBar() {
                hideProgressDialog();
            }

            @Override
            public void onUploadComplete() {
                createTopic(topic);

            }
        });
        fileUpLoad.run();

    }


    private void createTopic(final Topic topic) {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        showProgressDialog("正在保存...");
        List<MyFile> uploadList = new ArrayList<>();
        for (MyFile myFile : totalSelectFile) {
            if (myFile.getStatus() != MyFile.FILE_STATUS_UPLOAD_FAIL) {//只要不是上传失败的，包括远程的，上传成功的，都给保存到服务端
                uploadList.add(myFile);
            }
        }
        topic.setMyFileList(uploadList);
        RetrofitManager.getInstance()
                .createRequest(TopicService.class)
                .publishLiveRoomTopic(topic)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        hideProgressDialog();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            btn_publish.setEnabled(true);
                            Log.e(TAG, "创建焦点失败：" + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            btn_publish.setEnabled(true);
                            Log.e(TAG, "发布到ES失败：" + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        btn_publish.setEnabled(false);
                        updateFileStatus(uploadList);
                        Log.d(TAG, "创建焦点失败" + result.getData().toString());
                        //   createTribe();
                        isSaved = true;
                        final LiveRoom liveRoom = new LiveRoom();
                        liveRoom.setId(result.getData().toString());
                        liveRoom.setChatId(result.getData().toString());
                        liveRoom.setTitle(topic.getTitle());
                        for (MyFile myFile : uploadList) {
                            String url = myFile.getUrl();
                            if (myFile.getType().equals(MyFile.FILE_TYPE_VIDEO)) {
                                //为视频类型
                                liveRoom.setVideo(url);
                                break;
                            } else {
                                liveRoom.setCover(url);
                                break;
                            }
                        }
                        liveRoom.setManagerId(UserProfileManager.getInstance().getLoginUserInfo().getuId());
                        liveRoom.setStatus(Constant.TOPIC_STATUS_WAIT_VERIFY);
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_LIVE_ROOM, liveRoom));
                        ConfirmDialog confirmDialog = new ConfirmDialog(CreateLiveRoomActivity.this, "提醒", "创建完成，进入审核状态，审核通过之前不能开放使用，仅发布者个人可以查看");
                        confirmDialog.show();
                        confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                            @Override
                            public void confirm() {
                                finish();
                            }
                        });


                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        btn_publish.setEnabled(true);
                        Log.e(TAG, "发布到ES失败：" + t.getMessage());
                        t.printStackTrace();
                        hideProgressDialog();
                        showToast(getString(R.string.system_busy));
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_PICTURE_CHOOSE:
                ArrayList<MyFile> pictureFiles = data.getParcelableArrayListExtra("pictureFiles");
                ArrayList<MyFile> videoFiles = data.getParcelableArrayListExtra("videoFiles");
                totalSelectFile.removeAll(selectRemoteVideos);
                selectRemoteVideos.clear();
                if (videoFiles != null && videoFiles.size() != 0) {
                    selectRemoteVideos.addAll(videoFiles);
                    totalSelectFile.addAll(0, videoFiles);
                    // picturesListView.refreshVideoItem(videoFiles.get(0));
                }
                totalSelectFile.removeAll(selectRemotePictures);
                selectRemotePictures.clear();
                if (pictureFiles != null && pictureFiles.size() != 0) {
                    selectRemotePictures.addAll(pictureFiles);
                    totalSelectFile.addAll(pictureFiles);
                }
                picturesListView.refresh();

                break;

            case REQUEST_CODE_RECORD_VIDEO:

                framePicPath = data.getStringExtra("coverPath");
                //视频本地路径
                String localVideoPath = data.getStringExtra("videoPath");
                videoSize = data.getIntExtra("videoSize", 0);
//----------------------------------------------------------------------分割线，上面是阿里百川短视频录制，下面是github开源短视频录制
//                    localVideoPath= data.getStringExtra(Constant.EXTRA_INFO_VIDEO_PATH);
//                    framePicPath=data.getStringExtra(Constant.EXTRA_INFO_FRAME_PICTURE_PATH);
                totalSelectFile.removeAll(selectLocalVideos);
                selectLocalVideos.clear();
                MyFile localVideoFile = new MyFile(localVideoPath, framePicPath, MyFile.FILE_TYPE_VIDEO, MyFile.FILE_STATUS_LOCAL);
                selectLocalVideos.add(localVideoFile);
                totalSelectFile.addAll(0, selectLocalVideos);//插到第一个的位置
                picturesListView.refresh();
                break;

            case REQUEST_CODE_LOCATION:
                double latitude = data.getDoubleExtra("latitude", 0);
                double longitude = data.getDoubleExtra("longitude", 0);
                latLng.setLatitude(latitude);
                latLng.setLongitude(longitude);
                str_address = data.getStringExtra("address");
                tv_address.setText(str_address);
                Log.d(TAG, "onActivityResult: 收到定位回传");
                break;
        }
    }

    @Override
    protected void onResume() {

        super.onResume();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
    }

    @Override
    public void onSelectRemoteFile() {
        ArrayList<MyFile> historySelectFile = new ArrayList<>();
        historySelectFile.addAll(totalSelectFile);//添加总的
        historySelectFile.removeAll(selectLocalVideos);
        historySelectFile.removeAll(selectLocalPictures);

        MyFileSelectActivity.startActivity(this, videoLimit - selectLocalVideos.size(), pictureLimit - selectLocalPictures.size(), false, historySelectFile, REQUEST_CODE_PICTURE_CHOOSE);

//        MyFileRepositoryDialog myFileRepositoryDialog = MyFileRepositoryDialog.newInstance(videoLimit - selectLocalVideos.size(), pictureLimit - selectLocalPictures.size(), historySelectFile);
//        myFileRepositoryDialog.show(getSupportFragmentManager(), "");
//        myFileRepositoryDialog.setListener(new MyFileRepositoryDialog.InteractionListener() {
//            @Override
//            public void onConfirm(ArrayList<MyFile> videoFiles, ArrayList<MyFile> pictureFiles) {
//
//                totalSelectFile.removeAll(selectRemoteVideos);
//                selectRemoteVideos.clear();
//                if (videoFiles.size() != 0) {
//                    selectRemoteVideos.addAll(videoFiles);
//                    totalSelectFile.addAll(0, videoFiles);
//                    // picturesListView.refreshVideoItem(videoFiles.get(0));
//                }
//                totalSelectFile.removeAll(selectRemotePictures);
//                selectRemotePictures.clear();
//                if (pictureFiles.size() != 0) {
//                    selectRemotePictures.addAll(pictureFiles);
//                    totalSelectFile.addAll(pictureFiles);
//                }
//                picturesListView.refresh();
//            }
//        });
    }

    @Override
    public void onPickNewPicture(int position) {

        // TODO: 2019/7/4
//        Matisse.from(CreateLiveRoomActivity.this)
//                .choose(MimeType.ofImage())
//                .countable(true)
//                .showSingleMediaType(true)
//                .maxSelectable(pictureLimit - selectRemotePictures.size())
//                .theme(R.style.choose_pictures_style)
//                // .addFilter(new (320, 320, 5 * Filter.K * Filter.K))
//                .gridExpectedSize(
//                        getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
//                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
//                .thumbnailScale(0.85f)
//                .imageEngine(new GlideEngine())
//                .forResult(REQUEST_CODE_PICTURE_CHOOSE);
        EasyPhotos.createAlbum(this, true, GlideEngine.getInstance())
                .setFileProviderAuthority("com.srbl.mytx.fileProvider")
                .setSelectedPhotos(selectPhotos)
                .setCount(9)
                .start(new SelectCallback() {
                    @Override
                    public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                        selectPhotos = photos;
                        totalSelectFile.removeAll(selectLocalPictures);
                        selectLocalPictures.clear();
                        for (Photo photo : photos) {
                            selectLocalPictures.add(new MyFile(photo.uri, MyFile.FILE_TYPE_PICTURE, MyFile.FILE_STATUS_LOCAL));
                        }
                        totalSelectFile.addAll(selectLocalPictures);
                        picturesListView.refresh();
                        previewSelectFilePageView.refresh();
                    }

                });

    }

    @Override
    public void onShowBigImage(MyFile targetPictureFile, Info info) {
        previewSelectFilePageView.showBigPictures(totalSelectFile.indexOf(targetPictureFile), info);
    }

    @Override
    public void onCreateVideo(View view, int position) {
        //拍摄短视频
        startRecordVideo();
    }

    @Override
    public void onShowVideo(MyFile targetVideoFile, int position) {
        //展示短视频
        showVideo(targetVideoFile.getUrl());

    }

    @Override
    public void onPictureRemove(int position, MyFile targetPictureFile) {
        if (targetPictureFile.getStatus() == MyFile.FILE_STATUS_REMOTE) {
            selectRemotePictures.remove(targetPictureFile);
        } else {
            selectLocalPictures.remove(targetPictureFile);
            //清除掉已选文件记录
            for (int i = 0; i < selectPhotos.size(); i++) {
                if (selectPhotos.get(i).uri.equals(targetPictureFile.getUri())) {
                    selectPhotos.remove(i);
                    break;
                }
            }
        }
        previewSelectFilePageView.refresh();
    }

    @Override
    public void onVideoRemove(int position, MyFile targetVideoFile) {
        if (targetVideoFile.getStatus() == MyFile.FILE_STATUS_REMOTE) {
            selectRemoteVideos.remove(targetVideoFile);
        } else {
            selectLocalVideos.remove(targetVideoFile);
        }
        previewSelectFilePageView.refresh();
    }

    @Override
    public Info onGetPhotoViewInfo(int position) {
        MyFile myFile = totalSelectFile.get(position);
        return picturesListView.getPositionInfo(myFile);
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPress();
            return true;

        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private void onBackPress() {
        if (previewSelectFilePageView.isShown()) {
            if (!previewSelectFilePageView.isShowAnimate()) {
                Info info = onGetPhotoViewInfo(previewSelectFilePageView.getCurrentItem());
                previewSelectFilePageView.hideBigPictures(info);
            }
            return;
        }
        if (isSaved) {
            finish();
            return;
        }

        String str_descruption = et_content.getText().toString().trim();
        if (!TextUtils.isEmpty(str_descruption) || totalSelectFile.size() > 0) {
            ConfirmDialog dialog = new ConfirmDialog(CreateLiveRoomActivity.this, "提醒", "放弃已经编辑好的内容？", true);
            dialog.show();
            dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                @Override
                public void confirm() {
                    finish();
                }
            });
        } else {
            finish();
        }
    }

    /**
     * 保存到服务后，把已经保存的图片的状态设置为 远程图片
     * 不然连续发布，服务端把图片当成新上传图片传，插入到数据库被报ID重复的错
     *
     * @param uploadList
     */
    private void updateFileStatus(List<MyFile> uploadList) {
        for (MyFile myFile : uploadList) {
            if (myFile.getStatus() == MyFile.FILE_STATUS_UPLOAD_SUCCESS) {
                myFile.setStatus(MyFile.FILE_STATUS_REMOTE);
                //从本地文件选择集合中  移动到  远程文件选择集合中，并刷新
                if (myFile.getType() == MyFile.FILE_TYPE_PICTURE) {
                    selectLocalPictures.remove(myFile);
                    selectRemotePictures.add(myFile);
                } else {
                    selectLocalVideos.remove(myFile);
                    selectRemoteVideos.add(myFile);
                }
                picturesListView.refresh();
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionsUtils.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onStart() {
        super.onStart();
        String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA};
        PermissionsUtils.getInstance().checkPermissions(this, permissions, this);

    }

    @Override
    public void onGranted() {

    }

    @Override
    public void onDenied(List<String> deniedPermissionList) {
        StringBuilder tips = new StringBuilder();
        for (String permission : deniedPermissionList) {
            if (Manifest.permission.ACCESS_FINE_LOCATION.equals(permission)) {
                tips.append("[位置] ");
            } else if (Manifest.permission.READ_EXTERNAL_STORAGE.equals(permission) || Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission)) {
                tips.append("[储存空间] ");
            } else if (Manifest.permission.RECORD_AUDIO.equals(permission)) {
                tips.append("[麦克风] ");
            } else if (Manifest.permission.CAMERA.equals(permission)) {
                tips.append("[相机] ");
            }
        }
        ConfirmDialog dialog = new ConfirmDialog(CreateLiveRoomActivity.this, "提醒", "使用 " + tips + "的权限被禁止，去设置？", "去设置", "取消", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivity(intent);
            }
        });
        dialog.setCancelListener(new ConfirmDialog.CancelListener() {
            @Override
            public void cancel() {
                finish();
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }
}
